<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/system' }">系统管理</el-breadcrumb-item>
        <el-breadcrumb-item>我的段位</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 1. 段位信息卡片 -->
    <el-row :gutter="20" style="margin: 20px 0;">
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="rank-card-header">
            <span class="card-title">当前段位</span>
          </div>
          <div class="rank-content" v-if="currentRank && checkRankFieldValid()"> 
            <div class="rank-icon">
              <img 
                :src="getRankIcon(currentRank.rankLevel)" 
                alt="段位图标" 
                width="120" 
                height="120"
                @error="handleImgError"
                crossorigin="anonymous"
              >
            </div>
            <div class="rank-name">
              {{ (currentRank.rankLevel || '未定义段位').replace(/\s+/g, ' ') }} {{ (currentRank.rankSubLevel || '').replace(/\s+/g, ' ') }}
            </div>
            <div class="exp-progress">
              <el-progress 
                :percentage="calcExpPercentage"  
                :stroke-width="10"
                :status="calcExpPercentage >= 100 ? 'success' : undefined"
                :show-text="false"
              ></el-progress>
              <div class="exp-text">
                经验值：{{ formatNumber(currentRank.currentExp) }} / {{ formatNumber(currentRank.needExp) }}
              </div>
            </div>
          </div>
          <div class="no-rank" v-else>
            <el-empty description="暂无有效段位数据"></el-empty>
          </div>
        </el-card>
      </el-col>

      <!-- 2. 段位变化统计卡片 -->
      <el-col :span="16">
        <el-card shadow="hover">
          <div class="rank-card-header">
            <span class="card-title">段位变化统计</span>
          </div>
          <div class="count-content" v-if="Array.isArray(changeCountList) && changeCountList.length > 0">
            <el-table :data="changeCountList" border size="mini" :show-header="false">
              <el-table-column prop="changeType" label="变化类型" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.changeType === '升段' ? 'success' : 'warning'">
                    {{ (scope.row.changeType || '未知类型').trim() }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="changeCount" label="次数">
                <template #default="scope">
                  <span class="count-number">{{ formatNumber(scope.row.changeCount) }} 次</span>
                </template>
              </el-table-column>
              <el-table-column prop="changeType" label="说明">
                <template #default="scope">
                  <span class="count-desc">
                    {{ scope.row.changeType === '升段' 
                      ? '继续保持，冲刺更高段位！' 
                      : '分析原因，下次争取升段～' 
                    }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="no-count" v-else>
            <el-empty description="暂无段位变化数据"></el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 3. 段位历史表格 -->
    <el-card shadow="hover">
      <div class="rank-card-header">
        <span class="card-title">段位历史变化</span>
      </div>
      <el-table 
        :data="rankHistoryList" 
        border 
        size="mini" 
        v-if="Array.isArray(rankHistoryList) && rankHistoryList.length > 0"
      >
        <el-table-column prop="createTime" label="变化时间" width="180">
          <template #default="scope">
            {{ parseTime(scope.row.createTime, '{yyyy}-{mm}-{dd} {hh}:{ii}:{ss}') || '未知时间' }}
          </template>
        </el-table-column>
        <el-table-column prop="beforeRank" label="变化前段位" width="150">
          <template #default="scope">{{ (scope.row.beforeRank || '无').trim() }}</template>
        </el-table-column>
        <el-table-column prop="afterRank" label="变化后段位" width="150">
          <template #default="scope">{{ (scope.row.afterRank || '无').trim() }}</template>
        </el-table-column>
        <el-table-column prop="changeType" label="变化类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.changeType === '升段' ? 'success' : 'warning'">
              {{ (scope.row.changeType || '未知').trim() }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="变化原因">
          <template #default="scope">{{ (scope.row.reason || '未记录').trim() }}</template>
        </el-table-column>
      </el-table>
      <div class="no-history" v-else> 
        <el-empty description="暂无段位历史记录"></el-empty>
      </div>
    </el-card>
  </div>
</template>

<script>
import studentRankApi from '@/api/system/studentRank'
import { parseTime } from '@/utils/index'
import { mapGetters } from 'vuex' 

export default {
  name: 'SysStudentRank',
  computed: {
    ...mapGetters(['id']), 
    calcExpPercentage() {
      // 修复：添加this关键字引用组件实例的currentRank
      if (!this.currentRank || !this.checkRankFieldValid()) return 0;
      const currentExp = this.formatNumber(this.currentRank.currentExp, true);
      const needExp = this.formatNumber(this.currentRank.needExp, true);
      return Math.min(Math.max(Math.round((currentExp / needExp) * 100), 0), 100);
    }
  },
  data() {
    return {
      currentRank: null,
      rankHistoryList: [],
      changeCountList: [],
      defaultRankIcon: 'https://picsum.photos/id/0/120/120'
    }
  },
  created() {
    this.initData();
  },
  methods: {
    initData() {
      if (!this.id) { 
        this.$message.error('获取用户信息失败，请刷新页面重试');
        return;
      }
      this.loadCurrentRank();
      this.loadRankHistory();
      this.loadRankChangeCount();
    },
    checkRankFieldValid() {
      const { currentExp, needExp, rankLevel } = this.currentRank;
      return typeof currentExp !== 'undefined' 
        && typeof needExp !== 'undefined' 
        && rankLevel 
        && !isNaN(this.formatNumber(currentExp, true)) 
        && !isNaN(this.formatNumber(needExp, true))
        && this.formatNumber(needExp, true) > 0;
    },
    formatNumber(value, isRaw = false) {
      if (value === null || value === undefined) return isRaw ? 0 : '0';
      const num = Number(String(value).replace(/[^\d.-]/g, ''));
      return isRaw ? (isNaN(num) ? 0 : num) : (isNaN(num) ? '0' : String(num));
    },
    loadCurrentRank() {
      studentRankApi.getCurrentRank({ userId: this.id }) 
        .then(response => {
          if (response && response.code === 200) {
            this.currentRank = response.data || {};
          } else {
            this.$message.warning('段位数据加载异常');
          }
        })
        .catch(error => {
          this.$message.error('获取段位失败：' + (error.msg || error.message || '网络错误'));
        });
    },
    loadRankHistory() {
      studentRankApi.getRankHistory({ userId: this.id })
        .then(response => {
          this.rankHistoryList = Array.isArray(response.data) ? response.data : [];
        })
        .catch(error => {
          this.$message.error('获取段位历史失败：' + (error.msg || '网络错误'));
        });
    },
    loadRankChangeCount() {
      studentRankApi.getRankChangeCount({ userId: this.id })
        .then(response => {
          this.changeCountList = Array.isArray(response.data) ? response.data : [];
        })
        .catch(error => {
          this.$message.error('获取段位统计失败：' + (error.msg || '网络错误'));
        });
    },
    getRankIcon(rankLevel) {
      if (!rankLevel) return this.defaultRankIcon;
      const rankIconMap = {
        '倔强青铜': 'https://picsum.photos/id/1/120/120',
        '秩序白银': 'https://picsum.photos/id/2/120/120',
        '荣耀黄金': 'https://picsum.photos/id/3/120/120',
        '尊贵铂金': 'https://picsum.photos/id/4/120/120',
        '永恒钻石': 'https://picsum.photos/id/5/120/120',
        '至尊星耀': 'https://picsum.photos/id/6/120/120',
        '最强王者': 'https://picsum.photos/id/7/120/120'
      };
      return rankIconMap[rankLevel] || this.defaultRankIcon;
    },
    handleImgError(e) {
      e.target.src = this.defaultRankIcon;
      e.target.crossOrigin = 'anonymous';
    }
  }
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Microsoft YaHei", "Heiti SC", sans-serif;
}

.page-header {
  margin-bottom: 20px;
}

.rank-card-header {
  margin-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 10px;
}

.card-title {
  font-size: 16px;
  font-weight: 700;
  color: #1f2d3d;
}

.rank-content {
  text-align: center;
  padding: 10px 0;
}

.rank-icon {
  margin: 0 auto 15px;
  transition: all 0.3s ease;
}

.rank-icon img {
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  object-fit: cover;
}

.rank-name {
  font-size: 20px;
  font-weight: 700;
  color: #1f2d3d;
  margin-bottom: 15px;
}

.exp-progress {
  margin: 0 20px;
}

.exp-text {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
  text-align: right;
}

.count-content {
  padding: 10px 0;
}

.count-number {
  font-size: 16px;
  font-weight: 700;
  color: #1f2d3d;
}

.count-desc {
  color: #666;
  font-size: 14px;
}

.no-rank, .no-count, .no-history {
  padding: 40px 0;
  text-align: center;
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

::v-deep .el-breadcrumb__inner,
::v-deep .el-card__body,
::v-deep .el-empty__description {
  font-family: "Microsoft YaHei", "Heiti SC", sans-serif !important;
}
::v-deep .el-table__cell {
  text-align: left;
  white-space: nowrap;
}
</style>
    